import axios from 'axios'
import { ElMessage } from 'element-plus'
const service = axios.create({
  baseURL: `${process.env.VUE_APP_BASE_API}`, // url = base url + request url
  timeout: 15000,
  withCredentials: true // send cookies when cross-domain requests
})
// Request interceptors
service.interceptors.request.use(
  (config) => {
    // Add X-Access-Token header to every request, you can add other custom headers here
    // let cookie = localStorage.getItem('cookie')
    // if (cookie) {
    //   if (config && config.headers) { // 多一步判断
    //     config.headers['cookie'] = cookie
    //   }
    // }
    return config
  },
  (error) => {
    Promise.reject(error)
  }
)

// Response interceptors
service.interceptors.response.use(
  (response) => {
    let res = response.data
    if (res.code === 200 || res.code === 801 || res.code === 802 || res.code === 803 || res.code === 800 || res.success) {
      return res
    } else {
      if (res.body) {
        if (res.body.code === 200) {
          return res
        } else {
          res = res.body
        }
      }
      ElMessage({
        message: res.message || 'Error',
        type: 'error',
        duration: 5000
      })
      return Promise.reject(res)
    }
  },
  (error) => {
    console.log(error);
    if (error.response.data) {
      if (error.response.data.code === 501) {
        return Promise.reject(error.response.data)
      }
      ElMessage({
        message: error.response.data.message,
        // message: error.response.data ? error.response.data.message : error.message,
        type: 'error',
        duration: 5000
      })
    } else {
      ElMessage({
        message: error.message,
        // message: error.response.data ? error.response.data.message : error.message,
        type: 'error',
        duration: 5000
      })
      return Promise.reject(error)
    }
  }
)

export default service